<?php

namespace App\Http\Middleware;

use App\Lib\Api;
use App\Service\SignService;
use Closure;

class ApiSignMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $paramSign = $request->input('sign', '');
        $paramTime = $request->input('time', 0);

        if($paramTime <= time() - 1800 || empty($paramSign)){
            return Api::error(Api::CODE_PARAM_ERROR);
        }

        $param = $request->except(['sign']);
        ksort($param);
        $paramStr = implode('', $param);
        $sign = md5($paramStr . SignService::API_KEY);

        if($paramSign != $sign){
            return Api::error(Api::CODE_SIGN_ERROR);
        }

        return $next($request);
    }
}
